package javabasic.test;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.httpclient.protocol.Protocol;
import org.apache.commons.httpclient.protocol.ProtocolSocketFactory;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.HttpClient;
import org.apache.http.client.config.AuthSchemes;
import org.apache.http.client.config.CookieSpecs;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.config.Registry;
import org.apache.http.config.RegistryBuilder;
import org.apache.http.conn.socket.ConnectionSocketFactory;
import org.apache.http.conn.socket.PlainConnectionSocketFactory;
import org.apache.http.conn.ssl.NoopHostnameVerifier;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.conn.ssl.TrustStrategy;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.InputStreamEntity;
import org.apache.http.entity.mime.HttpMultipartMode;
import org.apache.http.entity.mime.MultipartEntity;
import org.apache.http.entity.mime.MultipartEntityBuilder;
import org.apache.http.entity.mime.content.FileBody;
import org.apache.http.entity.mime.content.InputStreamBody;
import org.apache.http.entity.mime.content.StringBody;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.impl.conn.BasicHttpClientConnectionManager;
import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
import org.apache.http.ssl.SSLContexts;
import org.apache.http.util.EntityUtils;
import org.junit.Test;

import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;
import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.charset.Charset;
import java.security.KeyManagementException;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.util.Arrays;
import java.util.Base64;
import org.apache.commons.httpclient.*;
import org.apache.commons.httpclient.methods.*;
import java.io.IOException;
import java.net.InetAddress;
import java.net.Socket;
import java.net.UnknownHostException;
import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManager;
import org.apache.commons.httpclient.ConnectTimeoutException;
import org.apache.commons.httpclient.HttpClientError;
import org.apache.commons.httpclient.params.HttpConnectionParams;
import org.apache.commons.httpclient.protocol.ControllerThreadSocketFactory;
import org.apache.commons.httpclient.protocol.SecureProtocolSocketFactory;

/**
 * @Author xiongmin
 * @Description //TODO
 * @Date 2020/4/8 16:28
 * @Version 1.0
 **/

class MyX509TrustManager implements X509TrustManager {

    @Override
    public void checkClientTrusted(X509Certificate[] x509Certificates, String s) throws CertificateException {

    }

    @Override
    public void checkServerTrusted(X509Certificate[] x509Certificates, String s) throws CertificateException {

    }

    @Override
    public X509Certificate[] getAcceptedIssuers() {
        return null;
    }
}
class MySecureProtocolSocketFactory implements SecureProtocolSocketFactory {

    //这里添加一个属性，主要目的就是来获取ssl跳过验证
    private SSLContext sslContext = null;
    /**
     * Constructor for MySecureProtocolSocketFactory.
     */
    public MySecureProtocolSocketFactory() {
    }
    /**
     * 这个创建一个获取SSLContext的方法，导入MyX509TrustManager进行初始化
     * @return
     */
    private static SSLContext createEasySSLContext() {
        try {
            SSLContext context = SSLContext.getInstance("SSL");
            context.init(null, new TrustManager[] { new MyX509TrustManager() },
                    null);
            return context;
        } catch (Exception e) {
            throw new HttpClientError(e.toString());
        }
    }

    /**
     * 判断获取SSLContext
     * @return
     */
    private SSLContext getSSLContext() {
        if (this.sslContext == null) {
            this.sslContext = createEasySSLContext();
        }
        return this.sslContext;
    }
    //后面的方法基本上就是带入相关参数就可以了
    /*
     * (non-Javadoc)
     *
     * @see org.apache.commons.httpclient.protocol.ProtocolSocketFactory#createSocket(java.lang.String,
     *      int, java.net.InetAddress, int)
     */
    public Socket createSocket(String host, int port, InetAddress clientHost,int clientPort) throws IOException, UnknownHostException {
        return getSSLContext().getSocketFactory().createSocket(host, port,clientHost, clientPort);
    }

    /*
     * (non-Javadoc)
     *
     * @see org.apache.commons.httpclient.protocol.ProtocolSocketFactory#createSocket(java.lang.String,
     *      int, java.net.InetAddress, int,
     *      org.apache.commons.httpclient.params.HttpConnectionParams)
     */
    public Socket createSocket(final String host, final int port,final InetAddress localAddress, final int localPort,
                               final HttpConnectionParams params) throws IOException,UnknownHostException, ConnectTimeoutException {
        if (params == null) {
            throw new IllegalArgumentException("Parameters may not be null");
        }
        int timeout = params.getConnectionTimeout();
        if (timeout == 0) {
            return createSocket(host, port, localAddress, localPort);
        } else {
            return ControllerThreadSocketFactory.createSocket(this, host, port,localAddress, localPort, timeout);
        }
    }

    /*
     * (non-Javadoc)
     *
     * @see SecureProtocolSocketFactory#createSocket(java.lang.String,int)
     */
    public Socket createSocket(String host, int port) throws IOException,UnknownHostException {
        return getSSLContext().getSocketFactory().createSocket(host, port);
    }

    /*
     * (non-Javadoc)
     *
     * @see SecureProtocolSocketFactory#createSocket(java.net.Socket,java.lang.String,int,boolean)
     */
    public Socket createSocket(Socket socket, String host, int port,boolean autoClose) throws IOException, UnknownHostException {
        return getSSLContext().getSocketFactory().createSocket(socket, host,port, autoClose);
    }
}

@Slf4j
public class UploadFile {

    /**
     * 依赖 commons-httpclient
     * @param URLString
     * @param filePath
     * @return
     * @throws Exception
     */
    public  int access(String URLString,String filePath) throws Exception {
        //声明
        ProtocolSocketFactory fcty = new MySecureProtocolSocketFactory();
        //加入相关的https请求方式
        Protocol.registerProtocol("https", new Protocol("https", fcty, 443));

        try
        {
            StringBuffer response = new StringBuffer();
//            HttpClient client = wrapClient(URLString);
            org.apache.commons.httpclient.HttpClient client = new org.apache.commons.httpclient.HttpClient();

            PostMethod method = new PostMethod(URLString);

            //设置Http Post数据，这里是上传文件
            File f=new File(filePath);
            FileInputStream fi=new FileInputStream(f);
            InputStreamRequestEntity fr=new InputStreamRequestEntity(fi);
            method.setRequestEntity((RequestEntity)fr);
            long length = fr.getContentLength();
            method.setRequestHeader("Authorization", getToken("admin:admin"));
            method.setRequestHeader("Content-Range", "0-"+(length-1)+"/"+(length));
            try
            {
                client.executeMethod(method); //这一步就把文件上传了
                System.out.println(new String(method.getResponseBody()));
                //下面是读取网站的返回网页，例如上传成功之类的
                if (method.getStatusCode() == HttpStatus.SC_OK)
                {
                    //读取为 InputStream，在网页内容数据量大时候推荐使用
                    BufferedReader reader = new BufferedReader(
                            new InputStreamReader(method.getResponseBodyAsStream(),
                                    "GBK"));
                    String line;
                    while ((line = reader.readLine()) != null)
                    {
                        response.append(line);
                    }
                    reader.close();
                }
            }
            catch (IOException e)
            {
                System.out.println("执行HTTP Post请求" + URLString + "时，发生异常！");
                e.printStackTrace();
            }
            finally
            {
                method.releaseConnection();
            }
            System.out.println("--------------------"+response.toString());
            return 1;
        }
        catch (Exception e)
        {
            e.printStackTrace();
            return -1;
        }
    }

    public void submitPost(String url, String filePath) throws IOException {
        String responseContent = "";
        HttpEntity httpEntity = null;
        int statusCode = 0;
        HttpClient httpClient = wrapClient(url);

        HttpPost httpPost = new HttpPost(url);
        File file = new File(filePath);
//        int length = File2byte(file).length;
        FileBody fileBody = new FileBody(file);
        MultipartEntity multipartEntity = new MultipartEntity();
        multipartEntity.addPart("file",fileBody);
        httpPost.setEntity(multipartEntity);
        long length = multipartEntity.getContentLength();
//        long length = inputStreamEntity.getContentLength();
        try {
            httpPost.addHeader("Authorization", getToken("admin:admin"));
//            httpPost.addHeader("Content-Type", "application/octet-stream");
            httpPost.addHeader("Connection", "keep-alive");
            httpPost.addHeader("Content-Range", "0-"+(length-1)+"/"+(length));
            HttpResponse response = httpClient.execute(httpPost);
            httpEntity = response.getEntity();
            responseContent = EntityUtils.toString(httpEntity);
            statusCode = response.getStatusLine().getStatusCode();
            log.info("HTTP Status Code:" + statusCode);
            log.info("responseContent = " + responseContent);
        } catch (IOException e) {
            e.printStackTrace();
        }

//        MultipartEntity multipartEntity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE,"--------------------HV2ymHFg03ehbqgZCaKO6jyH", Charset.defaultCharset());
////        multipartEntity.addPart("ram",new StringBody("4654646", Charset.forName("UTF-8")));
////        multipartEntity.addPart("key",new StringBody("123456",Charset.forName("UTF-8")));
////        multipartEntity.addPart("from",new StringBody("cw",Charset.forName("UTF-8")));
//        multipartEntity.addPart("file",new FileBody(new File(filePath)));
//
//        HttpPost request = new HttpPost(url);
//        request.setEntity(multipartEntity);
//        request.addHeader("Content-Type","multipart/form-data; boundary=--------------------HV2ymHFg03ehbqgZCaKO6jyH");
//        request.addHeader("Authorization", getToken("admin:admin"));
////        DefaultHttpClient httpClient = new DefaultHttpClient();
//        HttpResponse response =httpClient.execute(request);
//        InputStream is = response.getEntity().getContent();
//        BufferedReader in = new BufferedReader(new InputStreamReader(is));
//        StringBuffer buffer = new StringBuffer();
//        String line = "";
//        while ((line = in.readLine()) != null) {
//            buffer.append(line);
//        }
//        System.out.println("发送消息收到的返回："+buffer.toString());

    }

    private static HttpClient wrapClient(String url) {
        HttpClient httpClient = HttpClientBuilder.create().build();
        if (url != null && url.startsWith("https://")) {
            return sslClient();
        }
        return httpClient;
    }

    private static HttpClient sslClient() {
        try {
            // 在调用SSL之前需要重写验证方法，取消检测SSL
            MyX509TrustManager trustManager = new MyX509TrustManager();
            SSLContext ctx = SSLContext.getInstance(SSLConnectionSocketFactory.TLS);
            ctx.init(null, new TrustManager[]{trustManager}, null);
            SSLConnectionSocketFactory socketFactory = new SSLConnectionSocketFactory(ctx, NoopHostnameVerifier.INSTANCE);
            // 创建Registry
            RequestConfig requestConfig = RequestConfig.custom().setCookieSpec(CookieSpecs.STANDARD_STRICT)
                    .setExpectContinueEnabled(Boolean.TRUE).setTargetPreferredAuthSchemes(Arrays.asList(AuthSchemes.NTLM, AuthSchemes.DIGEST))
                    .setProxyPreferredAuthSchemes(Arrays.asList(AuthSchemes.BASIC)).build();
            Registry<ConnectionSocketFactory> socketFactoryRegistry = RegistryBuilder.<ConnectionSocketFactory>create()
                    .register("http", PlainConnectionSocketFactory.INSTANCE)
                    .register("https", socketFactory).build();
            // 创建ConnectionManager，添加Connection配置信息
            PoolingHttpClientConnectionManager connectionManager = new PoolingHttpClientConnectionManager(socketFactoryRegistry);
            CloseableHttpClient closeableHttpClient = HttpClients.custom().setConnectionManager(connectionManager)
                    .setDefaultRequestConfig(requestConfig).build();
            return closeableHttpClient;
        } catch (KeyManagementException ex) {
            throw new RuntimeException(ex);
        } catch (NoSuchAlgorithmException ex) {
            throw new RuntimeException(ex);
        }
    }



    @Test
    public void test() {
//        uploadFile("CoinCombinations.txt");

        String wxUrlStr="https://192.168.1.115/mgmt/shared/file-transfer/uploads/";
        String formName="text";
        String fileFullPath="D:\\javawork\\javabasic\\src\\main\\test\\com\\javabasic\\test\\CoinCombinations.txt";
        String fileName = "CoinCombinations.txt";
//        upload(wxUrlStr+"CoinCombinations.txt",formName,fileFullPath);

        try {
//            doPost(wxUrlStr+"CoinCombinations.txt",File2byte(new File(fileFullPath)),fileName);
//            doPost(wxUrlStr+"CoinCombinations.txt",fileFullPath);
//            upload1(wxUrlStr+"CoinCombinations.txt",fileFullPath);
//            submitPost(wxUrlStr+"CoinCombinations.txt",fileFullPath);
//            access(wxUrlStr+"CoinCombinations.txt",fileFullPath);
            access(wxUrlStr+"server.crt","D:\\server.crt");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    public String upload1(String url,String filePath){
        String fdfsPath = "";
        try {

            TrustStrategy acceptingTrustStrategy = (cert, authType) -> true;
            SSLContext sslContext = SSLContexts.custom().loadTrustMaterial(null, acceptingTrustStrategy).build();
            SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslContext, NoopHostnameVerifier.INSTANCE);

            Registry<ConnectionSocketFactory> socketFactoryRegistry =
                    RegistryBuilder.<ConnectionSocketFactory>create()
                            .register("https", sslsf)
                            .register("http", new PlainConnectionSocketFactory())
                            .build();

            BasicHttpClientConnectionManager connectionManager =
                    new BasicHttpClientConnectionManager(socketFactoryRegistry);
            CloseableHttpClient httpclient = HttpClients.custom().setSSLSocketFactory(sslsf)
                    .setConnectionManager(connectionManager).build();

//            HttpClient httpclient = new DefaultHttpClient();

            HttpPost httppost = new HttpPost(url);
            httppost.addHeader("Connection", "keep-alive");
            httppost.addHeader("Authorization", getToken("admin:admin"));


            File file = new File(filePath);
            String name = file.getName();
            InputStream in = new FileInputStream(file);
            MultipartEntity reqEntity = new MultipartEntity();
            InputStreamBody inputStreamBody = new InputStreamBody(in,name);
            StringBody fileNam = new StringBody(name);
//            StringBody dateFlag = new StringBody("20160122152301");
//            StringBody datumType = new StringBody("0");
//            StringBody uploadWay = new StringBody("0");
//            StringBody userId = new StringBody("0538");
//            StringBody tenderId = new StringBody("2315");
//            StringBody metrialsType = new StringBody("25");
//            StringBody ip = new StringBody("0.0.0.1");
//            StringBody driverName = new StringBody("huawei");
//            StringBody systemVersion = new StringBody("djf");
//            StringBody position = new StringBody("信息路38",  Charset.forName("utf8"));
            //文件流
            reqEntity.addPart("datums", inputStreamBody);
            reqEntity.addPart("fileName", fileNam);
//            reqEntity.addPart("dateFlag", dateFlag);
//            reqEntity.addPart("datumType", datumType);
//            reqEntity.addPart("uploadWay", uploadWay);
//            reqEntity.addPart("userId", userId);
//            reqEntity.addPart("tenderId", tenderId);
//            reqEntity.addPart("metrialsType", metrialsType);
//            reqEntity.addPart("ip", ip);
//            reqEntity.addPart("driverName", driverName);
//            reqEntity.addPart("systemVersion", systemVersion);
//            reqEntity.addPart("position", position);

            httppost.setEntity(reqEntity);
            HttpResponse response = httpclient.execute(httppost);
            int statusCode = response.getStatusLine().getStatusCode();

            if(statusCode == HttpStatus.SC_OK){

                System.out.println("服务器正常响应.....");

                HttpEntity resEntity = response.getEntity();
                System.out.println(EntityUtils.toString(resEntity));//httpclient自带的工具类读取返回数据

                System.out.println(resEntity.getContent());

                EntityUtils.consume(resEntity);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "";
    }


    public static byte[] File2byte(File tradeFile){
        byte[] buffer = null;
        try
        {
            FileInputStream fis = new FileInputStream(tradeFile);
            ByteArrayOutputStream bos = new ByteArrayOutputStream();
            byte[] b = new byte[1024];
            int n;
            while ((n = fis.read(b)) != -1)
            {
                bos.write(b, 0, n);
            }
            fis.close();
            bos.close();
            buffer = bos.toByteArray();
        }catch (FileNotFoundException e){
            e.printStackTrace();
        }catch (IOException e){
            e.printStackTrace();
        }
        return buffer;
    }

    public String doPost(String url, String pathName) throws Exception {
        //拿到fileName拼接URL
        StringBuffer sb=new StringBuffer();
//        final String url = sb.append(EmailGradeTask.EMAILGRADETASKUPLOADURL).append(fileName).toString();
        //创建HttpClient实例
        TrustStrategy acceptingTrustStrategy = (cert, authType) -> true;
        SSLContext sslContext = SSLContexts.custom().loadTrustMaterial(null, acceptingTrustStrategy).build();
        SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslContext, NoopHostnameVerifier.INSTANCE);

        Registry<ConnectionSocketFactory> socketFactoryRegistry =
                RegistryBuilder.<ConnectionSocketFactory>create()
                        .register("https", sslsf)
                        .register("http", new PlainConnectionSocketFactory())
                        .build();

        BasicHttpClientConnectionManager connectionManager =
                new BasicHttpClientConnectionManager(socketFactoryRegistry);
        CloseableHttpClient httpClient = HttpClients.custom().setSSLSocketFactory(sslsf)
                .setConnectionManager(connectionManager).build();


//        CloseableHttpClient httpClient = HttpClients.createDefault();
        //创建post方法连接实例，在post方法中传入待连接地址
        HttpPost httpPost = new HttpPost(url);
        CloseableHttpResponse response = null;
        httpPost.addHeader("Connection", "keep-alive");
        httpPost.addHeader("Authorization", getToken("admin:admin"));


        FileBody fileBody = new FileBody(new File(pathName));
        StringBody stringBody = new StringBody("文件的描述");
        MultipartEntity entity = new MultipartEntity();
        entity.addPart("file", fileBody);
        entity.addPart("desc", stringBody);
        httpPost.setEntity(entity);
        response = httpClient.execute(httpPost);
        if(HttpStatus.SC_OK==response.getStatusLine().getStatusCode()){

            HttpEntity entitys = response.getEntity();
            if (entity != null) {
                System.out.println(entity.getContentLength());
                System.out.println(EntityUtils.toString(entitys));
            }
        }

        return "文件上传错误";
    }


    public void upload(String urlStr, String  formName,String fileName) {
        try {
            // 换行符
            final String newLine = "\r\n";
            final String boundaryPrefix = "--";
            // 定义数据分隔线
            String BOUNDARY = "========7d4a6d158c9";
            // 服务器的域名
            URL url = new URL(urlStr);
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            // 设置为POST情
            conn.setRequestMethod("POST");
            // 发送POST请求必须设置如下两行
            conn.setDoOutput(true);
            conn.setDoInput(true);

            // 设置请求头参数
            conn.setRequestProperty("connection", "Keep-Alive");
            conn.setRequestProperty("Charsert", "UTF-8");
            conn.setRequestProperty("Content-Type","multipart/form-data; boundary=" + BOUNDARY);
            conn.setRequestProperty("Authorization",getToken("admin:admin"));
            OutputStream out = conn.getOutputStream();
            // 上传文件
            File file = new File(fileName);
            StringBuilder sb = new StringBuilder();
            sb.append(boundaryPrefix);
            sb.append(BOUNDARY);
            sb.append(newLine);
            // 文件参数,photo参数名可以随意修改
//            sb.append("Content-Disposition: form-data;name=\""+formName+"\";filename=\""+ fileName + "\"" + newLine);
            sb.append("Content-Type:application/octet-stream");
            // 参数头设置完以后需要两个换行，然后才是参数内容
            sb.append(newLine);
            sb.append(newLine);
            // 将参数头的数据写入到输出流中
            out.write(sb.toString().getBytes());
            // 数据输入流,用于读取文件数据
            DataInputStream in = new DataInputStream(new FileInputStream(file));
            byte[] bufferOut = new byte[1024];
            int bytes = 0;
            // 每次读1KB数据,并且将文件数据写入到输出流中
            while ((bytes = in.read(bufferOut)) != -1) {
                out.write(bufferOut, 0, bytes);
            }
            // 最后添加换行
            out.write(newLine.getBytes());
            in.close();
            // 定义最后数据分隔线，即--加上BOUNDARY再加上--。
            byte[] end_data = (newLine + boundaryPrefix + BOUNDARY
                    + boundaryPrefix + newLine).getBytes();
            // 写上结尾标识
            out.write(end_data);
            out.flush();
            out.close();

            //定义BufferedReader输入流来读取URL的响应
            BufferedReader reader = new BufferedReader(new InputStreamReader(
                    conn.getInputStream()));
            String line = null;
            while ((line = reader.readLine()) != null) {
                System.out.println(line);
            }
        } catch (Exception e) {
            System.out.println("发送POST请求出现异常！" + e);
            e.printStackTrace();
        }
    }


    public void uploadFile(String fileName) {
        try {

            // 换行符
            final String newLine = "\r\n";
            final String boundaryPrefix = "--";
            // 定义数据分隔线
            String BOUNDARY = "========7d4a6d158c9";
            String urlStr = "https://192.168.1.115/mgmt/shared/file-transfer/uploads/";
            urlStr += fileName;

            // 服务器的域名
            URL url = new URL(urlStr);
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            // 设置为POST情
            conn.setRequestMethod("POST");
            // 发送POST请求必须设置如下两行
            conn.setDoOutput(true);
            conn.setDoInput(true);
            conn.setUseCaches(false);
            // 设置请求头参数
            conn.setRequestProperty("connection", "Keep-Alive");
            conn.setRequestProperty("Charsert", "UTF-8");
            conn.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + BOUNDARY);
            conn.setRequestProperty("Authorization", getToken("admin:admin"));

            OutputStream out = new DataOutputStream(conn.getOutputStream());

            // 上传文件
            File file = new File(fileName);
            StringBuilder sb = new StringBuilder();
            sb.append(boundaryPrefix);
            sb.append(BOUNDARY);
            sb.append(newLine);
            // 文件参数,photo参数名可以随意修改
            sb.append("Content-Disposition: form-data;name=\"photo\";filename=\"" + fileName
                    + "\"" + newLine);
            sb.append("Content-Type:application/octet-stream");
            // 参数头设置完以后需要两个换行，然后才是参数内容
            sb.append(newLine);
            sb.append(newLine);

            // 将参数头的数据写入到输出流中
            out.write(sb.toString().getBytes());

            // 数据输入流,用于读取文件数据
            DataInputStream in = new DataInputStream(new FileInputStream(
                    file));
            byte[] bufferOut = new byte[1024];
            int bytes = 0;
            // 每次读1KB数据,并且将文件数据写入到输出流中
            while ((bytes = in.read(bufferOut)) != -1) {
                out.write(bufferOut, 0, bytes);
            }
            // 最后添加换行
            out.write(newLine.getBytes());
            in.close();

            // 定义最后数据分隔线，即--加上BOUNDARY再加上--。
            byte[] end_data = (newLine + boundaryPrefix + BOUNDARY + boundaryPrefix + newLine)
                    .getBytes();
            // 写上结尾标识
            out.write(end_data);
            out.flush();
            out.close();

            // 定义BufferedReader输入流来读取URL的响应
//            BufferedReader reader = new BufferedReader(new InputStreamReader(
//                    conn.getInputStream()));
//            String line = null;
//            while ((line = reader.readLine()) != null) {
//                System.out.println(line);
//            }

        } catch (Exception e) {
            System.out.println("发送POST请求出现异常！" + e);
            e.printStackTrace();
        }
    }

    public String getToken(String auth) {
        byte[] encodeAuth = Base64.getEncoder().encode(auth.getBytes(Charset.forName("UTF-8")));
        String authHeader = "Basic " + new String(encodeAuth);
        return authHeader;
    }
}
